﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GenericControlsWinForm
{
    public class CEPTextBox : TextBox
    {
        public CEPTextBox()
        {
            //Evento que vai verificar se a letra pode ser inserida
            this.KeyPress += new KeyPressEventHandler(CEPTextBox_KeyPress);
            //Evento que vai formatar a string
            this.KeyUp += new KeyEventHandler(CEPTextBox_KeyUp);
            this.LostFocus += new EventHandler(CEPTextBox_LostFocus);
            this.MaxLength = 9;
            this.Width = 65;
        }

        void CEPTextBox_LostFocus(object sender, EventArgs e)
        {
            if (!this.Text.Contains('-') || this.Text.Length != 9)
                this.Text = String.Empty;
        }

        void CEPTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                e.Handled = !CommomValidator.CharIsNumber(e.KeyChar);
            }
            catch (Exception)
            {
                throw new Exception("Erro no componente CEP.");
            }
        }

        void CEPTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (CommomValidator.KeyIsNumber(e.KeyCode))
                {
                    int selectionStart = this.SelectionStart;
                    bool contaisHifen = this.Text.Contains('-');

                    string texto = this.Text.Replace("-", "");
                    string newText;
                    if (texto.Length > 5)
                    {
                        newText = texto.Substring(0, 5);
                        newText += "-";
                        newText += texto.Substring(5);
                        if (newText.Length > 9)
                            newText = newText.Substring(0, 9);

                        this.Text = newText;

                        if (!contaisHifen && selectionStart > 5)
                            selectionStart++;
                    }
                    else
                        this.Text = texto;
                    
                    this.SelectionStart = selectionStart;
                }
            }
            catch (Exception)
            {
                throw new Exception("Erro no componente CEP.");
            }
        }
    }
}
